package com.changgou.order.service.impl;

import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.feign.SpuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.goods.pojo.Spu;
import com.changgou.order.pojo.OrderItem;
import com.changgou.order.service.CartService;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 描述
 *
 * @author www.itheima.com
 * @version 1.0
 * @package com.changgou.order.service.impl *
 * @since 1.0
 */
@Service
public class CartServiceImpl implements CartService {



    @Autowired
    private RedisTemplate redisTemplate;

    //创建feign (SKUfeign SPU的feign)
    @Autowired
    private SkuFeign skuFeign;

    @Autowired
    private SpuFeign spuFeign;
    /***
     * 加入购物车
     * @param num:购买商品数量
     * @param id：购买ID
     * @param username：购买用户
     * @return
     */
    @Override
    public void add(Long id, Integer num, String username) {
        //删除该商品的购物车数据
        if(num<=0){
            redisTemplate.boundHashOps("Cart_"+username).delete(id);
            return;
        }

        Result<Sku> skuResult = skuFeign.findById(id);
        if(skuResult!=null && skuResult.isFlag()){
            //获取SKU
            Sku sku = skuResult.getData();
            Result<Spu> spuResult = spuFeign.findById(sku.getSpuId());

            //将SKU转成OrderItem
            OrderItem orderItem =  sku2OrderItem(sku,spuResult.getData(),num);


            //购物车数据存入到Redis
            // namespace = Cart_[username]
            //key=id(sku)
            //value=OrderItem
            redisTemplate.boundHashOps("Cart_"+username).put(id,orderItem);

        }


    }

    /**
     * sku转OrderItem
     * @param sku
     * @param spu
     * @param num
     * @return
     */
    private OrderItem sku2OrderItem(Sku sku, Spu spu, Integer num) {
        OrderItem orderItem = new OrderItem();
        orderItem.setSpuId(sku.getSpuId());
        orderItem.setSkuId(sku.getId());
        orderItem.setName(sku.getName());
        orderItem.setPrice(sku.getPrice());
        orderItem.setNum(num);
        orderItem.setMoney(num*orderItem.getPrice());
        //单价*数量
        orderItem.setPayMoney(num*orderItem.getPrice());    //实付金额
        orderItem.setImage(sku.getImage());
        orderItem.setWeight(sku.getWeight()*num);           //重量=单个重量*数量
        //分类ID设置
        orderItem.setCategoryId1(spu.getCategory1Id());
        orderItem.setCategoryId2(spu.getCategory2Id());
        orderItem.setCategoryId3(spu.getCategory3Id());
        return orderItem;
    }

    @Override
    public List<OrderItem> list(String username) {
        List<OrderItem> orderItemList = redisTemplate.boundHashOps("Cart_" + username).values();
        return orderItemList;
    }
}
